import axios from 'axios';
import { getToken } from './token';
import { message } from 'antd';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

// 创建 axios 实例
const api = axios.create({
    baseURL: 'http://localhost:3000/api',
    timeout: 10000,
    headers: { 'Content-Type': 'application/json' }
});

// 请求拦截器
api.interceptors.request.use(
    (config) => {
        NProgress.start();
        const token = getToken();
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        NProgress.done();
        return Promise.reject(error);
    }
);

// 响应拦截器
api.interceptors.response.use(
    (response) => {
        NProgress.done();
        return response.data;
    },
    (error) => {
        NProgress.done();
        if (error.response?.data?.error) {
            message.error(error.response.data.error);
        } else {
            message.error('请求失败');
        }
        return Promise.reject(error);
    }
);

// 通用请求封装
const http = {
    get: (url, params = {}, config = {}) => api.get(url, { params, ...config }),
    post: (url, data = {}, config = {}) => api.post(url, data, config),
    put: (url, data = {}, config = {}) => api.put(url, data, config),
    delete: (url, params = {}, config = {}) => api.delete(url, { params, ...config }),
};

export default http;
